import {
  ds
} from "../../../../tools/data"
import {
  users
} from "../../../../tools/users"
import {
  pages
} from '../../../../tools/pages'
import {
  checkTool
} from "../../../../tools/check"
import {
  ui
} from "../../../../tools/ui";
import {
  resource
} from '../../../../static/resource'
import {
  pay
} from '~/tools/pay'
import {
  coupon
} from '~/tools/coupon'

Page({
  data: {
    action: 'new',
    id: '',
    item: {},
    errMsg: "",
    specList: [],
    desc: [],
    ticket: {}
  },
  async init() {
    const that = this

    if (this.data.action == 'edit') {
      ds.coll('coupons')
        .where({
          _id: ds.cmd.eq(that.data.id)
        })
        .get()
        .then((res) => {
          // console.log(res)
          const item = res.data[0]
          that.setData({
            item
          })
        })
    }
  },
  onPickStartDate(e) {
    const {
      txt,
      timestamp
    } = e.detail
    const item = this.data.item
    item.start = timestamp
    this.setData({
      item
    })
  },
  onPickEndDate(e) {
    const {
      txt,
      timestamp
    } = e.detail
    const item = this.data.item
    item.end = timestamp
    this.setData({
      item
    })
  },
  onChooseGoodsTap() {
    wx.navigateTo({
      url: '/pages/common/goodsManage/index',
    })
  },
  goodsSelected(goods) {
    const item = this.data.item
    item.goodsId = (goods ? goods.id : undefined)
    item.goodsTitle = (goods ? goods.title : undefined)
    this.setData({
      item
    })
  },
  onChooseUserTap() {
    wx.navigateTo({
      url: '/pages/usercenter/staff/index?action=select',
    })
  },
  userSelected(user) {
    // console.log(user)
    const item = this.data.item
    item.userId = (user ? user._id : undefined)
    item.userName = (user ? user.personInfo?.nickName : undefined)
    this.setData({
      item
    })
  },
  addSpec() {
    const specList = this.data.specList
    specList.push({});
    this.setData({
      specList
    });
  },
  delSpec(e) {
    const specList = this.data.specList
    specList.splice(e.target.dataset.index, 1)
    this.setData({
      specList
    })
  },
  selImg(tag) {
    wx.navigateTo({
      url: `/pages/common/imgSelect/index?tag=${tag}`
    })
  },
  addImgClick() {
    this.setData({
      imgClickIndex: -1
    })
    this.selImg()
  },
  imgClick(e) {
    this.setData({
      imgClickIndex: e.target.dataset.index
    })
    this.selImg()
  },
  imgSelected(files, tag) {
    if (files.length <= 0) return;
    // console.log(files)

    const that = this
    const imgIndex = this.data.imgClickIndex
    // console.log(imgIndex)

    const item = that.data.item || {}
    const images = item.images || []
    if (imgIndex >= 0) images[imgIndex] = files[0]
    else images.push(files[0])
    item.images = images
    that.setData({
      item
    })

  },
  save() {
    if (!checkTool.check(this.getFields())) return

    const {
      item,
      result
    } = this.data

    item.thumb = item.images[0] || ''
    if (item.amount) {
      item.num = Number(item.amount) // 余量（非群专属券，下单页面之间领取）
      item.left = Number(item.amount) // 余量（群专属券领用）
    }
    coupon.setupDuration(item)
    // console.log(item, this.data.id)
    if (result == 'json') {
      return pages.back(prePage => {
        item._id = item._id || pay.genUuid(32, 16)
        if (prePage.couponCreated) prePage.couponCreated(item)
      })
    }
    ui.loading()
    ds.cloudUpdate('coupons', this.data.id, item, res => {
      // console.log(res)
      const success = res.result.errMsg.endsWith(':ok')
      ui.loading(false)
      ui.toast(success, success ? '' : res.result.errMsg, () => {
        pages.back(prePage => {
          if (prePage.init) prePage.init()
        })
      })
    })
  },
  getFields() {
    const {
      item
    } = this.data
    const fields = [{
      value: item.images,
      fn: images => images?.length > 0,
      title: '图片'
    }, {
      value: item.title,
      title: '标题'
    }, {
      value: item.unit,
      regex: checkTool.CommonRegex.integer,
      title: '满减'
    }, {
      value: item.minus,
      regex: checkTool.CommonRegex.integer,
      title: '满减'
    }, {
      value: item.amount,
      allowEmpty: true,
      regex: checkTool.CommonRegex.integer,
      title: '发布数量'
    }, {
      value: item.days,
      allowEmpty: true,
      regex: checkTool.CommonRegex.integer,
      title: '有效期'
    }, {
      value: item.limit,
      allowEmpty: true,
      regex: checkTool.CommonRegex.integer,
      title: '领用限量'
    }]
    return fields
  },
  durationTap(e) {
    if (!e.target.id) return
    this.setData({
      'item.duration': e.target.id,
    })
  },
  daysChange(e) {
    this.setData({
      'item.days': e.detail.value,
      'item.duration': 'days'
    })
  },
  onAddDesc(e) {
    const imgClickIndex = -1
    this.setData({
      imgClickIndex
    })
    this.selImg('desc')
  },
  onDelDesc(e) {
    const index = e.target.dataset.index
    const desc = this.data.desc
    desc.splice(index, 1)
    this.setData({
      desc
    })
  },
  onClickDesc(e) {
    const imgClickIndex = e.target.dataset.index
    this.setData({
      imgClickIndex
    })
    this.selImg('desc')
  },
  onDel() {
    ui.confirm('确定删除吗？', res => {
      if (!res) return

      ui.loading()
      ds.cloudRemove('coupons', {
        _id: this.data.id
      }, res => {
        // console.log('del')
        pages.back(prePage => {
          prePage.init()
        })
      })
    })

  },
  onTicketBtnTap() {
    wx.navigateTo({
      url: '../ticketEdit/ticketEdit?ticket=' + JSON.stringify(this.data.ticket),
    })
  },
  onValueChange(e) {
    const that = this
    const name = e.target.dataset.name
    let value = e.detail.value
    if (name == 'tags') {
      value = value.replaceAll(' ', '').split(/[,，]/);
    }

    this.data.item[name] = value
    this.setData({
      item: that.data.item
    })
    // console.log(this.data.item)
  },
  onSpecChange(e) {
    const specList = this.data.specList
    const name = e.target.dataset.name,
      index = e.target.dataset.index
    specList[index][name] = e.detail.value
    this.setData({
      specList
    })
  },
  onDelImg(e) {
    const index = e.target.dataset.index
    const images = this.data.item.images
    images.splice(index, 1)
    this.setData({
      item: {
        images
      }
    })
  },
  ticketCallback(values) {
    this.setData({
      ticket: values
    })
    // console.log(this.data.ticket)
  },
  onLoad(option) {
    // console.log(option)
    wx.showShareMenu({
      withShareTicket: true
    })

    if (option.action) {
      this.setData({
        action: option.action,
        id: option.id
      })
    }
    if (option.openGId) {
      this.setData({
        item: {
          openGId: option.openGId
        }
      })
    }
    if (option.item) {
      this.setData({
        item: {
          ...this.data.item,
          ...JSON.parse(option.item)
        },
        result: option.result
      })
    }
    // console.log(this.data)
    this.init();
  },
  onShareAppMessage() {
    const item = this.data.item
    if (!item?._id || !item.openGId) return

    return {
      title: `群专属满${item.unit}减${item.minus}`,
      imageUrl: resource.img.couponCover,
      path: `/pages/usercenter/coupon/obtain/obtain?id=${item._id}`
    }
  }
});